//https://www.cnblogs.com/idreamo/p/9249367.html
//https://www.cnblogs.com/en-heng/p/49929
import * as bfun from '../../core/fbyte.js';
/**
 * 邹工的lz78 算法 37798955@qq.com
 * 仅适合表小于255的情况 大与255时 必须提升索引字节位数,不一定能够压缩哦
 * 放弃这种编码
 * @param {Object} winsize
 */


const Lz78 = function(winsize) {
	winsize = winsize || 54; //窗口缓存	
	winsize = winsize > 255 ? 255 : winsize; //限制宽度
	let self = this;
	self.encode = function(message) {
		let tree_dict = new Map();
		let m_len = message.length,
			i = 0,
			n = 0,
			b1, c1, k, k1,
			j = 0,
			list = [];
		while (i < m_len) {
			b1 = message[i];
			c1 = b1.toString();
			k = tree_dict.get(c1);
			if (k == null) {
				tree_dict.set(c1, ++n);
				list.push([0, b1]);
				i++;
			} else if (i == m_len - 1) {
				i++;
			} else {
				//console.log(j,i);
				k1 = k;
				for (j = i + 1; j < m_len; j++, k1 = k) {
					b1 = message.subarray(i, j + 1);
					c1 = b1.toString();
					k = tree_dict.get(c1);
					//console.log(k1,k,b1[b1.length-1])
					if (k == null) {
						tree_dict.set(c1, ++n);
						i = j + 1;
						//注意k1 如果 大于255 一个字节是放不下的
						list.push([k1, b1[b1.length - 1]]);
						break
					} else if (j == m_len - 1) {
						i = j + 1;
					}
				}
			}
		}
		let arr = list.flat();
		console.log(tree_dict); //
		return new Uint8Array(arr);
	};

	self.decode = function(ui8) {
		let tree_dict = new Map(),
			list = [];
		let b2j = 0,
			n = 1; //已经读取到的字符
		let a, b, c, zf;
		for (let i = 0; i < ui8.length; i += 2) {
			a = ui8[i]; //索引
			b = ui8[i + 1]; //字符
			if (a == 0) {
				tree_dict.set(n++, [b]);
				list.push(b);
			} else {
				zf = tree_dict.get(a);
				c = zf.slice(0);
				c.push(b);
				tree_dict.set(n++, c);
				list.push(c);
			}
		}
		console.log(tree_dict)
		return new Uint8Array(list.flat());
	};
	return self;
}
export default Lz78;
